#coding=utf-8
__author__ = 'liubin'

from tornado.web import authenticated, asynchronous
from sqlalchemy import or_, desc, and_
from sqlalchemy.orm import joinedload
from tornado_json.requesthandlers import APIHandler
from project.tools import HandlerMixin, unblock, to_json
from project.models import Category


class CategoryHandler(HandlerMixin, APIHandler):
    """
    布料种类API
    """
    __url_names__ = []

    @asynchronous
    def check_name_not_exist(self, name):
        """
        检查编码存在
        """
        record = self.db_conn.query(Category).filter_by(name=name, isDeleted=False).first()
        if record:
            self.error(u'指定种类已经被使用')
            return False
        return True

    @asynchronous
    def check_id_exist(self, id):
        """
        检查ID存在
        """
        record = self.db_conn.query(Category).filter_by(id=id, isDeleted=False).first()
        if not record:
            self.error(u'指定种类不存在')
        return record


class SingleHandler(CategoryHandler):
    """
    单条记录处理
    """
    __urls__ = [r"/api/category/(?P<id>[a-zA-Z0-9_]+)/?"]

    @authenticated
    @unblock
    def get(self, id):
        """
        获得单条记录
        :param id:
        :return:
        """
        record = self.check_id_exist(id)
        if record:
            self.success(to_json(record))

    @authenticated
    @unblock
    def put(self, id):
        """
        更新单条记录
        :param id:
        :return:
        """
        record = self.check_id_exist(id)
        if record:
            data = self.json_args
            print(data)
            record.name = data.get('name')
            record.comment = data.get('comment')
            self.db_conn.commit()
            self.success(None)

    @authenticated
    @unblock
    def delete(self, id):
        """
        删除
        """
        record = self.check_id_exist(id)
        if record:
            record.isDeleted = True
            self.db_conn.commit()
            self.success(None)


class ListHandler(CategoryHandler):
    """
    记录列表
    """
    __urls__ = [r'/api/category/?']

    @authenticated
    @unblock
    def get(self):
        """
        获取记录列表
        :return:
        """
        # 无关字段, 原样返回
        draw = self.get_query_argument('draw', 0)
        # 分页大小
        size = int(self.get_query_argument('size', 0))
        # 第几项开始
        start = int(self.get_query_argument('start', 0))
        # 查询字段
        query = self.get_query_argument('query', '')
        # 排序字段
        order = self.get_query_argument('order', '')
        # 正序或倒叙
        sort = self.get_query_argument('dir', '')
        end = start + size
        records = self.db_conn.query(Category).filter_by(isDeleted=False)
        if query:
            records = records.filter(
                or_(
                    Category.name.like('%' + query + '%'),
                    Category.comment.like('%' + query + '%')
                )
            )
        if order:
            if sort == 'desc':
                records = records.order_by(desc(getattr(Category, order)))
            else:
                records = records.order_by(getattr(Category, order))
        # 总件数
        total = records.count()
        if end:
            # 分页处理
            records = records.slice(start, end)
        # 获取list对象
        records = records.all()
        # 返回值
        self.success(to_json(records), draw=draw, total=total)

    @authenticated
    @unblock
    def post(self):
        """
        新增
        :return:
        """
        record = Category(self.json_args)
        #if self.check_name_not_exist(record.name):
        self.db_conn.add(record)
        self.db_conn.commit()
        self.success(None)